package com.xuecheng.manage_course.service;

import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.CourseMarket;
import com.xuecheng.framework.domain.system.SysDictionary;
import com.xuecheng.framework.domain.system.SysDictionaryValue;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.dao.CourseBaseRepository;
import com.xuecheng.manage_course.dao.CourseMarketRepository;
import com.xuecheng.manage_course.feign.cms.SysDictionaryFeign;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;
import java.util.Scanner;

@Service
public class CourseMarketService {
    @Value("${xuecheng.dictionary_url}")
    private String dictionary_url;

    @Value("${xuecheng.course_chargingRules_type}")
    private String course_chargingRules_type;

    @Value(("${xuecheng.course_expirationDate_type}"))
    private String course_expirationDate_type;
    @Resource
    private CourseMarketRepository courseMarketRepository;
    @Resource
    private CourseBaseRepository courseBaseRepository;
    @Resource
    SysDictionaryFeign sysDictionaryFeign;
    /**
     * 根据课程id查询课程营销信息
     *
     * @param courseId 课程id
     * @return 查询课程营销信息
     */
    public CourseMarket getCourseMarketById(@PathVariable("courseId") String courseId) {
        Optional<CourseMarket> optional = courseMarketRepository.findById(courseId);
        return optional.orElse(null);
    }


    /**
     * 根据课程id更新课程信息
     *
     * @param id           课程id
     * @param courseMarket 课程实体类
     * @return 添加是否成功
     */
    public ResponseResult updateCourseMarket(String id, CourseMarket courseMarket) {
        // 校验课程id是否存在
        Optional<CourseBase> optional = courseBaseRepository.findById(id);
        if (!optional.isPresent()){
            // 传入了无效的课程id
            return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
        }
        // 校验数据字典的合法性
        try {
            boolean flag = this.checkSysDictionary(courseMarket);
            if (flag){
                // 数据字典合法,校验数据合法性
                if ("203001".equals(courseMarket.getCharge())){
                    // 课程免费就不应该出现价格
                    courseMarket.setPrice(0D);
                }
                // 校验有效期是否合法
                if ("204001".equals(courseMarket.getValid())){
                    // 课程永久有效就不应该有结束时间
                    courseMarket.setEndTime(null);
                    // 课程永久有效的时间开始时间为当前时间
                    courseMarket.setStartTime(new Date());
                }else {
                    // 检测结束时间是不是在开始时间之前
                    if (courseMarket.getStartTime().after(courseMarket.getEndTime())
                            || courseMarket.getStartTime().toString().equals(courseMarket.getEndTime().toString())){
                        return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
                    }
                }
                courseMarketRepository.save(courseMarket);
                return new ResponseResult(CommonCode.SUCCESS);
            }else {
                return new ResponseResult(CommonCode.INVALID_JSON_PARAMETER);
            }
        }catch (Exception e){
            // 远程校验信息失败
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }
    }

    /**
     * 根据dictionary_url 和  course_grade_type 查询数据字典信息 并且校验实体类中数据字典数据是否合法
     * @param courseMarket 需要校验的实体类
     * @return 校验成功返回true,失败返回false
     */
    public boolean checkSysDictionary(CourseMarket courseMarket) throws Exception {
        SysDictionary chargingRules = sysDictionaryFeign.findSysDictionaryByType(course_chargingRules_type);
        SysDictionary expirationDate = sysDictionaryFeign.findSysDictionaryByType(course_expirationDate_type);
        if (chargingRules.getDValue().size()==0 || expirationDate.getDValue().size()==0){
            return false;
        }else {
            SysDictionaryValue charging = chargingRules.getDValue().stream().filter(e -> e.getSdId().equals(courseMarket.getCharge())).findFirst().orElse(null);
            SysDictionaryValue expiration = expirationDate.getDValue().stream().filter(e -> e.getSdId().equals(courseMarket.getValid())).findFirst().orElse(null);
            return charging != null && expiration != null;
        }
    }
}
